<template>
  <span>
    <el-input v-if="mode==='input'" v-model="userNames" disabled :placeholder="placeholder">
      <template slot="append">
        <el-button @click="handleSelectUser"><i class="el-icon-user" /></el-button>
      </template>
    </el-input>
    <el-button v-if="mode==='button'" plain type="primary" :icon="icon" @click="handleSelectUser">{{ text }}</el-button>
    <i v-if="mode==='icon'" :class="icon" class="common-cursor color-danger" @click="handleSelectUser" />

    <model-dialog
      title="用户选择器"
      :visible.sync="dialogVisible"
      width="1000px"
      @close="dialogVisible=!dialogVisible">
      <div class="flex-main">
        <div class="conmmon-container-main">
          <!--搜索条件-->
          <div class="filter-container">
            <el-form :model="listQuery" :inline="true">
              <el-form-item>
                <el-input v-model="listQuery.userName" placeholder="请输入用户名" class="filter-item" @keyup.enter.native="handleFilter" />
              </el-form-item>
              <el-form-item>
                <el-input v-model="listQuery.realName" placeholder="请输入真实姓名" class="filter-item" @keyup.enter.native="handleFilter" />
              </el-form-item>
              <el-form-item>
                <el-input v-model="listQuery.mobile" placeholder="请输入手机号" class="filter-item" @keyup.enter.native="handleFilter" />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="el-icon-search" @click="handleFilter">搜索</el-button>
                <el-button icon="el-icon-refresh" @click="handleReset">重置</el-button>
              </el-form-item>
            </el-form>
          </div>
          <!--列表-->
          <div class="table-container flex-main">
            <el-table
              ref="multipleTable"
              :data="list"
              header-cell-class-name="table-header"
              fit
              highlight-current-row
              @selection-change="handleSelectionChange"
              @sort-change="sortChange">
              <el-table-column v-if="multiple" type="selection" width="50" align="center" />
              <el-table-column align="center" prop="id" width="60" label="#">
                <template slot-scope="scope">{{ scope.$index+1 }}</template>
              </el-table-column>
              <el-table-column :show-overflow-tooltip="true" label="头像" prop="avatar" width="70" align="center">
                <template slot-scope="scope">
                  <img :src="global.getFileView(scope.row.avatar)" class="common-round-image-32" :title="scope.row.realName" @error="handleImageError">
                </template>
              </el-table-column>
              <el-table-column :show-overflow-tooltip="true" label="用户名" sortable prop="userName" min-width="200" />
              <el-table-column :show-overflow-tooltip="true" label="真实姓名" prop="realName" width="90" />
              <el-table-column :show-overflow-tooltip="true" label="手机号码" prop="mobile" width="110" align="center" />
              <el-table-column label="性别" prop="gender" width="100">
                <template slot-scope="scope">{{ scope.row.gender==0 ?'保密': scope.row.gender==1 ? '男' : '女' }}</template>
              </el-table-column>
              <el-table-column label="岗位" prop="job" width="100" :show-overflow-tooltip="true">
                <template slot-scope="scope">{{ scope.row.job?(scope.row.job.split(":")[1]) :'' }}</template>
              </el-table-column>
              <el-table-column align="center" prop="gmtCreated" width="150" sortable label="加入时间">
                <template slot-scope="scope">{{ scope.row.gmtCreated | formatDate }}</template>
              </el-table-column>
              <el-table-column v-if="!multiple" align="center" width="90" label="操作" fixed="right">
                <template slot-scope="scope">
                  <button-option skin="primary" title="选择用户" @click="confirmSelectSingle(scope.row)">选择</button-option>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div class="pagination_handler">
            <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="fetchData" />
          </div>
        </div>
      </div>
      <template v-if="multiple" slot="footer">
        <el-button type="primary" @click="confirmSelect">确 定</el-button>
      </template>
    </model-dialog>
  </span>
</template>
<script>
export default {
  props: {
    value: {
      type: String,
      default: ''
    },

    // 模式  按钮、文本框、图标
    mode: {
      type: String,
      default: 'button'
    },
    icon: {
      type: String,
      default: 'el-icon-user'
    },
    text: {
      type: String,
      default: '选择用户'
    },
    placeholder: {
      type: String,
      default: '请选择人员'
    },
    orgId: {
      type: String,
      default: ''
    },

    multiple: {
      type: Boolean,
      default() {
        return false
      }
    }
  },
  data() {
    return {
      dialogVisible: false,
      list: null,
      total: 0,
      listQuery: {
        page: 1,
        limit: this.common.PAGE_LIMIT_DEFAULT,
        sort: this.common.SORT_DEFAULT,
        userName: '',
        realName: '',
        mobile: ''
      },
      multipleSelectionRecords: [],
      userDetails: null,
      userNames: null,
      selectIds: []

    }
  },
  watch: {
    userDetails: function(val) {
      this.$emit('input', val)
    },
    value: function(val) {
      this.analysisUserResult(val)
    }
  },
  created() {
    this.analysisUserResult(this.value)
  },
  methods: {
    analysisUserResult(val) {
      if (val) {
        var names = []
        this.selectIds = []
        val.split(';').forEach((item) => {
          names.push(item.split(':')[1])
          this.selectIds.push(item.split(':')[0])
        })
        this.userNames = names.join('、')
      } else {
        this.$nextTick(() => {
          this.userNames = null
          this.selectIds = []
        })
      }
    },
    handleSelectUser() {
      this.dialogVisible = true
      this.fetchData()
      this.$nextTick(() => {
        this.$refs.multipleTable.clearSelection()
        if (this.selectIds.length > 0) {
          if (this.list) {
            this.list.forEach((item) => {
              if (this.selectIds.includes(item.id)) {
                this.$refs.multipleTable.toggleRowSelection(item, true)
              }
            })
          }
        }
      })
    },
    selectedOrg(val) {
      this.currentSelectedOrg = val
    },
    confirmSelect() {
      if (this.multipleSelectionRecords.length !== 0) {
        if (!this.multiple && this.multipleSelectionRecords.length > 1) {
          this.msgWarning('只能选择一条用户记录')
          return
        }
        var users = []

        var names = []
        var ids = []
        var userDetails = []
        this.multipleSelectionRecords.forEach((item) => {
          names.push(item.realName)
          ids.push(item.id)
          userDetails.push(item.id + ':' + item.realName)
          users.push({
            id: item.id,
            avatar: item.avatar,
            realName: item.realName,
            userName: item.userName,
            mobile: item.mobile
          })
        })
        if (this.multiple) {
          this.$emit('selectUser', users)
        } else {
          this.$emit('selectUser', users[0])
        }
        this.userNames = names.join('、')
        this.userDetails = userDetails.join(';')
        this.dialogVisible = false
      } else {
        this.msgWarning('请选择用户')
        return
      }
    },
    confirmSelectSingle(row) {
      this.$emit('selectUser', {
        id: row.id,
        avatar: row.avatar,
        realName: row.realName,
        userName: row.userName,
        mobile: row.mobile
      })
      this.userNames = row.realName
      this.userDetails = `${row.id}:${row.realName}`
      this.dialogVisible = false
    },
    /**
     * 全选/反选
     */
    handleSelectionChange(val) {
      this.multipleSelectionRecords = val
    },

    async fetchData() {
      this.listQuery = {
        ...this.listQuery,
        orgId: this.orgId
      }
      const response = await this.$store.dispatch('userPage', this.listQuery)
      this.list = response.records
      this.$nextTick(() => {
        if (this.selectIds.length > 0) {
          this.list.forEach((item) => {
            if (this.selectIds.includes(item.id)) {
              console.log(item)

              this.$refs.multipleTable.toggleRowSelection(item, true)
            }
          })
        }
      })
      this.total = response.total
    },
    // 固定写法
    sortChange({ prop, order }) {
      if (prop) {
        if (order === 'ascending') {
          this.listQuery.sort = '+' + prop
        } else {
          this.listQuery.sort = '-' + prop
        }
      } else {
        this.listQuery.sort = this.common.SORT_DEFAULT
      }
      this.handleFilter()
    },
    // 固定写法
    handleCommand(val) {
    },
    /**
     * 搜索
     */
    handleFilter() {
      this.listQuery.page = 1
      this.fetchData()
    },
    /**
     * 重置
     */
    handleReset() {
      this.listQuery = {
        page: 1,
        limit: this.common.PAGE_LIMIT_DEFAULT,
        sort: this.common.SORT_DEFAULT,
        userName: '',
        realName: '',
        mobile: ''
      }
      this.fetchData()
    }
  }
}
</script>
<style scoped>
    #userSelector{

    }
</style>
